package com.cooper.resource.download;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import com.cooper.android.comm.BitmapUtils;
import com.cooper.scraper.R;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class DownloadItemAdapter extends BaseAdapter implements
		DownloadListener {

	private List<DownloadStatus> downItems = new ArrayList<DownloadStatus>();
	private Context context;
	private DownloadControl control;
	private List<DownItemViewHolder> viewItems = new ArrayList<DownItemViewHolder>();

	public DownloadItemAdapter(Context context, DownloadControl control) {
		super();
		this.context = context.getApplicationContext();
		this.control = control;

		postGetDownItems(false);
	}

	private Handler handler = new Handler();

	private void postGetDownItems(boolean notifyDataSetChanged) {
		Collection<DownloadStatus> items = control.getDownloading();
		if (items == null) {
			handler.postDelayed(new Runnable() {

				@Override
				public void run() {
					postGetDownItems(true);

				}
			}, 1000);
		} else {
			downItems.addAll(items);
			if (notifyDataSetChanged)
				this.notifyDataSetChanged();
		}
	}

	/*
	 * 
	 * public void addDownload(DownloadStatus downItem) {
	 * 
	 * downItems.add(downItem); notifyDataSetChanged();
	 * 
	 * }
	 */

	@Override
	public int getCount() {
		return downItems.size();
	}

	@Override
	public Object getItem(int position) {
		return downItems.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		DownItemViewHolder result;
		if (convertView == null) {
			result = new DownItemViewHolder(context);

		} else {
			result = (DownItemViewHolder) convertView.getTag();
		}
		setItemViewInitStatus(result, downItems.get(position));
		return result.rootView;
	}

	@Override
	public synchronized void onBegin(DownloadStatus res) {
		onUpdate(res);
	}

	@Override
	public synchronized void onComplete(DownloadStatus res) {
		Collections.sort(downItems, DownloadComparator.getInstance());
		notifyDataSetChanged();
		onUpdate(res);
	}

	@Override
	public synchronized void onUpdate(DownloadStatus res) {
		DownItemViewHolder holder = getItemViewHolder(res);
		if (holder != null && res != null) {
			holder.setStatus(res);
		}
	}

	@Override
	public synchronized void onFail(DownloadStatus res) {
		onUpdate(res);
	}

	public void removeItem(DownloadStatus status) {
		downItems.remove(status);
		for (DownItemViewHolder divh : viewItems) {
			if (divh.status == status) {
				viewItems.remove(divh);
				break;
			}
		}
		notifyDataSetChanged();
	}

	public void removeAll() {
		downItems.clear();
		viewItems.clear();
		notifyDataSetChanged();
	}

	private DownItemViewHolder getItemViewHolder(DownloadStatus item) {
		for (DownItemViewHolder vi : viewItems) {
			if (vi.getStatus().equals(item)) {
				return vi;
			}
		}
		Log.d("DownloadItemAdapter", "item is not found:" + item);
		return null;
	}

	private void setItemViewInitStatus(DownItemViewHolder holder,
			DownloadStatus item) {
		List<DownItemViewHolder> removeVI = new ArrayList<DownItemViewHolder>();
		for (DownItemViewHolder vi : viewItems) {
			if (vi.getStatus() != null && vi.getStatus().equals(item)) {
				vi.cleanStatus();
				removeVI.add(vi);
			}
		}
		for (DownItemViewHolder vi : removeVI) {
			viewItems.remove(vi);
		}
		holder.setStatus(item);
		if (!viewItems.contains(holder)) {
			viewItems.add(holder);
		}
	}

	private class DownItemViewHolder {

		public View rootView;
		public ImageView thumb;
		public TextView title;
		public TextView subTitle;
		public ProgressBar progressBar;
		public ImageButton controlButton;
		public ImageButton cancelButton;

		private DownloadStatus status = null;

		public DownloadStatus getStatus() {
			return status;
		}

		public void cleanStatus() {
			status = null;
		}

		private void loadThumb(DownloadStatus status) {
			Bitmap thumbBitmap = status.getThumb(
					BitmapUtils.dip2px(context.getResources(), 40),
					BitmapUtils.dip2px(context.getResources(), 50));
			if (thumbBitmap != null) {
				thumb.setImageBitmap(thumbBitmap);
			} else
				thumb.setImageResource(R.drawable.down_no_thumb);
		}

		public void setStatus(DownloadStatus status) {
			if (this.status != status) {
				loadThumb(status);
			}

			this.status = status;
			controlButton.setEnabled(true);
			title.setText(status.getDownloadResource().getDownloadTitle());

			if (status.getDownloadResource().isFinish()) {
				progressBar.setIndeterminate(false);
				progressBar.setProgress(100);

				controlButton.setTag(new Integer(3));
				controlButton.setImageResource(R.drawable.ic_complete_d);
				subTitle.setText(R.string.download_finish);

			} else {
				switch (status.getStatus()) {
				case DownloadStatus.STATUS_FAIL:
					controlButton.setTag(new Integer(1));
					controlButton.setImageResource(R.drawable.ic_continue_d);
					subTitle.setText(status.getFailReason());
					break;
				case DownloadStatus.STATUS_DOWNLOADING:
					if (!status.getDownloadResource().isPrepared()) {
						subTitle.setText(R.string.download_prepare);
					} else {
						subTitle.setText(R.string.downloading);
					}
					controlButton.setTag(new Integer(0));
					controlButton.setImageResource(R.drawable.ic_pause_d);
					break;
				case DownloadStatus.STATUS_WAITING:
					subTitle.setText(R.string.download_waiting);
					controlButton.setEnabled(false);
					break;
				case DownloadStatus.STATUS_STOP:
					subTitle.setText(R.string.download_stoped);
					controlButton.setTag(new Integer(1));
					controlButton.setImageResource(R.drawable.ic_continue_d);
					break;
				}

				if (status.getDownloadResource().getTotalSize() <= 0) {
					if (status.getStatus() == DownloadStatus.STATUS_FAIL) {
						progressBar.setIndeterminate(false);
						progressBar.setProgress(0);
					} else
						progressBar.setIndeterminate(true);
				} else {
					progressBar.setIndeterminate(false);
					progressBar
							.setProgress((int) ((new Float(status
									.getDownloadResource().getDownLen()) / new Float(
									status.getDownloadResource().getTotalSize())) * 100));

				}
			}
		}

		public DownItemViewHolder(Context context) {
			super();
			LayoutInflater mInflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			rootView = mInflater.inflate(R.layout.download_item, null);
			rootView.setTag(this);
			thumb = (ImageView) rootView.findViewById(R.id.thumb);

			title = (TextView) rootView.findViewById(R.id.title);
			subTitle = (TextView) rootView.findViewById(R.id.subtitle);
			subTitle.setText(R.string.download_waiting);
			progressBar = (ProgressBar) rootView.findViewById(R.id.progressBar);
			controlButton = (ImageButton) rootView
					.findViewById(R.id.controlButton);
			controlButton.setTag(new Integer(0));
			controlButton.setImageResource(R.drawable.ic_pause_d);
			controlButton.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (v.getTag().equals(new Integer(0))) {
						subTitle.setText(R.string.download_stoping);
						control.pause(status);

						v.setTag(new Integer(1));
						controlButton
								.setImageResource(R.drawable.ic_continue_d);
						controlButton.setEnabled(false);
					} else if (v.getTag().equals(new Integer(1))) {
						subTitle.setText(R.string.download_waiting);
						control.downContinue(status);
						v.setTag(new Integer(0));
						controlButton.setImageResource(R.drawable.ic_pause_d);
					} else {
						if (status.getDownloadResource().isFinish()) {
							control.completeMove(status);
						}
					}

				}
			});
			cancelButton = (ImageButton) rootView
					.findViewById(R.id.cancelButton);
			cancelButton.setImageResource(R.drawable.ic_delete_d);
			cancelButton.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					control.cancel(status);
				}
			});
		}

	}

	@Override
	public void onThumbComplete(DownloadStatus res) {
		DownItemViewHolder holder = getItemViewHolder(res);
		if (holder != null && res != null) {
			holder.loadThumb(res);
		}

	}

}
